package com.bytedance.common.plugin.framework.util;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.bytedance.common.plugin.PluginDepend;
import com.bytedance.common.plugin.component.MyResources;
import com.bytedance.common.plugin.framework.model.ProcessType;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.reflect.Reflect;

import org.json.JSONArray;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class PluginUtil {
    private static Method mMethod_apply;
    private static ProcessType sMyProcessType;

    static {
        ProcessType processType = null;
        try {
            PluginUtil.mMethod_apply = SharedPreferences.Editor.class.getMethod("apply");
        } catch (NoSuchMethodException e) {
            PluginUtil.mMethod_apply = null;
        }
        PluginUtil.sMyProcessType = processType;
    }

    public PluginUtil() {

    }

    private static PackageInfo readCertificate(PackageManager packageManager, File file) {
        PackageInfo packageInfo;
        if (packageManager == null) {
            return null;
        }

        packageInfo = packageManager.getPackageArchiveInfo(file.getAbsolutePath(), 69);
        if (packageInfo != null && packageInfo.signatures == null) {
            try {
                packageInfo.signatures = PluginUtil.getSignature(file);
            } catch (IOException ioException) {
                Logger.e("Plugin", "Error retrieving signatures of " + file + ".", ioException);
            }
        }
        return packageInfo;
    }

    private static boolean delete(File file) {
        if (file != null && file.exists() && file.isDirectory()) {
            String[] children = file.list();
            int length = children.length;
            for (int i = 0; i < length; i++) {
                File child = new File(file, children[i]);
                if (child.isDirectory()) {
                    PluginUtil.delete(child);
                } else {
                    child.delete();
                }
            }
            return file.delete();
        }

        return false;
    }

    private static Certificate[] readCertificate(JarFile jarFile, JarEntry jarEntry) {
        Certificate[] certificates = null;
        byte[] bytes = new byte[4096];
        InputStream inputStream = null;
        try {
            inputStream = jarFile.getInputStream(jarEntry);
            do {
            } while (inputStream.read(bytes, 0, 4096) != -1);
            if (jarEntry == null) {
                return null;
            }
            certificates = jarEntry.getCertificates();
        } catch (RuntimeException e) {
            Logger.w("Plugin", "Exception reading " + jarFile.getName(), e);
        } catch (IOException e) {
            Logger.w("Plugin", "Exception reading " + jarEntry.getName() + " in " + jarFile.getName(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return certificates;
    }

    public static void apply(SharedPreferences.Editor editor) {
        if (PluginUtil.mMethod_apply != null) {
            try {
                PluginUtil.mMethod_apply.invoke(editor);
                return;
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        editor.commit();
    }

    private static Signature[] getSignature(File file) throws IOException {
        Signature[] signatures = null;
        try {
            JarFile jarFile = new JarFile(file);
            Certificate[] certificates = PluginUtil.readCertificate(jarFile, jarFile.getJarEntry("AndroidManifest.xml"));
            jarFile.close();
            if (certificates != null && certificates.length > 0) {
                signatures = new Signature[certificates.length];
                int i = 0;
                while (i < certificates.length) {
                    signatures[i] = new Signature(certificates[i].getEncoded());
                    ++i;
                    continue;
                }
                return signatures;
            }
            Logger.e("Plugin", "Package has no certificates!");
        } catch (CertificateEncodingException e) {
            Logger.w("Plugin", "Exception reading " + file, e);
        }

        return signatures;
    }

    public static String bytes2Hex(byte[] bytes) {
        int i = 0;
        if (bytes != null) {
            try {
                StringBuilder stringBuilder = new StringBuilder();
                int length = bytes.length;
                while (i < length) {
                    stringBuilder.append(String.format("%02x", Byte.valueOf(bytes[i])));
                    ++i;
                }
                return stringBuilder.toString();
            } catch (Throwable throwable) {
            }
        }

        return null;
    }

    public static void copyFile(File source, File dst) {
        FileChannel v1 = null;
        FileOutputStream v7 = null;
        FileInputStream v8 = null;
        FileChannel v6 = null;
        try {
            v8 = new FileInputStream(source);
            v7 = new FileOutputStream(dst);
            v1 = v8.getChannel();
            v6 = v7.getChannel();
            v1.transferTo(0, v1.size(), v6);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                v1.close();
                v6.close();
                v7.close();
                v8.close();
            } catch (IOException v0_1) {
                v0_1.printStackTrace();
            }
        }
    }

    public static boolean deleteFile(File arg1) {
        boolean v0;
        if (arg1 == null) {
            v0 = false;
        } else {
            if ((arg1.isFile()) && (arg1.exists())) {
                return arg1.delete();
            }

            v0 = PluginUtil.delete(arg1);
        }

        return v0;
    }

    public static String fileToMD5(File arg7) {
        int v3;
        FileInputStream v1_2 = null;
        String v0 = null;
        int v2 = 0;
        try {
            v1_2 = new FileInputStream(arg7);
            v3 = 1024;
            byte[] v3_1 = new byte[v3];
            MessageDigest v4 = MessageDigest.getInstance("MD5");
            while (v2 != -1) {
                v2 = ((InputStream) v1_2).read(v3_1);
                if (v2 <= 0) {
                    continue;
                }

                v4.update(v3_1, 0, v2);
            }

            v0 = PluginUtil.bytes2Hex(v4.digest());
        } catch (Throwable v0_1) {

        } finally {

            try {
                ((InputStream) v1_2).close();
            } catch (Exception v1_1) {
            }
        }
        return v0;
    }

    public static ActivityInfo getActivityInfo(Context arg2, String arg3) throws PackageManager.NameNotFoundException {
        return PluginUtil.getActivityInfo(PluginUtil.getPkgInfo(arg2, arg3), 0);
    }

    public static ActivityInfo getActivityInfo(PackageInfo arg1, int arg2) {
        return arg1.activities[arg2];
    }

    public static ActivityInfo getActivityInfo(Context arg1, String arg2, int arg3) throws PackageManager.NameNotFoundException {
        return PluginUtil.getActivityInfo(PluginUtil.getPkgInfo(arg1, arg2), arg3);
    }

    public static Drawable getAppIcon(Context arg4, String arg5) throws PackageManager.NameNotFoundException {
        Drawable v0_1;
        PackageManager v0 = arg4.getPackageManager();
        PackageInfo v1 = PluginUtil.getPkgInfo(arg4, arg5);
        if (v1 == null) {
            v0_1 = null;
        } else {
            ApplicationInfo v1_1 = v1.applicationInfo;
            if (Build.VERSION.SDK_INT >= 8) {
                v1_1.sourceDir = arg5;
                v1_1.publicSourceDir = arg5;
            }

            v0_1 = v0.getApplicationIcon(v1_1);
        }

        return v0_1;
    }

    public static CharSequence getAppName(Context arg4, String arg5) throws PackageManager.NameNotFoundException {
        CharSequence v0_1;
        PackageManager v0 = arg4.getPackageManager();
        PackageInfo v1 = PluginUtil.getPkgInfo(arg4, arg5);
        if (v1 == null) {
            v0_1 = null;
        } else {
            ApplicationInfo v1_1 = v1.applicationInfo;
            if (Build.VERSION.SDK_INT >= 8) {
                v1_1.sourceDir = arg5;
                v1_1.publicSourceDir = arg5;
            }

            v0_1 = v0.getApplicationLabel(v1_1);
        }

        return v0_1;
    }

    public static ApplicationInfo getApplicationInfo(Context arg3, String arg4, PackageInfo[] arg5) throws PackageManager.NameNotFoundException {
        ApplicationInfo v0_1;
        PackageInfo v0 = arg5 == null || arg5.length == 0 ? PluginUtil.getPkgInfo(arg3, arg4) : arg5[0];
        if (v0 == null) {
            v0_1 = null;
        } else {
            v0_1 = v0.applicationInfo;
            if (Build.VERSION.SDK_INT >= 8) {
                v0_1.sourceDir = arg4;
                v0_1.publicSourceDir = arg4;
            }
        }

        return v0_1;
    }

    public static StackTraceElement getCallerStackTraceElement() {
        return Thread.currentThread().getStackTrace()[4];
    }

    public static StackTraceElement getCurrentStackTraceElement() {
        return Thread.currentThread().getStackTrace()[3];
    }

    public static CharSequence getPackageName(Context arg3, String arg4) throws PackageManager.NameNotFoundException {
        CharSequence v0_1;
        PackageInfo v0 = PluginUtil.getPkgInfo(arg3, arg4);
        if (v0 == null) {
            v0_1 = null;
        } else {
            ApplicationInfo v0_2 = v0.applicationInfo;
            if (Build.VERSION.SDK_INT >= 8) {
                v0_2.sourceDir = arg4;
                v0_2.publicSourceDir = arg4;
            }

            v0_1 = v0_2.packageName;
        }

        return v0_1;
    }

    public static PackageInfo getPkgInfo(Context arg2, String arg3) throws PackageManager.NameNotFoundException {
        PackageInfo v0 = TextUtils.isEmpty(((CharSequence) arg3)) ? null : PluginUtil.readCertificate(arg2.getPackageManager(), new File(arg3));
        return v0;
    }

    public static Application getPluginApplication(Context context, String arg9) throws PackageManager.NameNotFoundException {
        Application v0_1;
        Application v1 = null;
        PackageInfo v0 = PluginUtil.getPkgInfo(context, arg9);
        if (v0 == null) {
            v0_1 = v1;
            return v0_1;
        }

        ClassLoader v2 = context.getClassLoader();
        if (v2 == null) {
            throw new IllegalArgumentException("Not found ClassLoader in plugin!");
        }

        try {
            Object v0_6 = v2.loadClass(v0.applicationInfo.className).newInstance();
            Reflect.on(v0_6).call("attachBaseContext", new Class[]{Context.class}, new Object[]{context.getApplicationContext()});
            return (Application) v0_6;
        } catch (ClassNotFoundException v0_3) {
        } catch (IllegalAccessException v0_4) {
        } catch (InstantiationException v0_5) {
        }

        return v1;
    }

    public static SharedPreferences getPluginPreferences(Context context) {
        return context.getSharedPreferences(
                com.bytedance.common.plugin.a.getPluginDepend().ssLitePluginSpName(),
                Context.MODE_MULTI_PROCESS);
    }

    public static ProcessType getProcessType(Context context) {
        if (context == null) {
            PluginUtil.sMyProcessType = ProcessType.OTHER;
        }

        if (PluginUtil.sMyProcessType != null) {
            return PluginUtil.sMyProcessType;
        } else {
            String curProcessName = com.bytedance.common.plugin.a.getPluginDepend().getCurProcessName(context);
            if (curProcessName != null && (curProcessName.equals(context.getPackageName()))) {
                PluginUtil.sMyProcessType = ProcessType.MAIN;
            } else if (PluginUtil.isWorkProcess(curProcessName)) {
                PluginUtil.sMyProcessType = ProcessType.WORK;
            } else {
                PluginUtil.sMyProcessType = ProcessType.OTHER;
            }
            return PluginUtil.sMyProcessType;
        }
    }

    public static boolean isWorkProcess(String processName) {
        return processName != null && processName.indexOf(":") != -1;
    }

    public static void logForActivityThread(Context arg11, String arg12) {
        int v2_1;
        AssetManager v5;
        Object v1_1;
        try {
            Object v0_1 = Reflect.onClass(Reflect.forName("android.app.ActivityThread")).call("currentActivityThread").target;
            if (v0_1 == null) {
                return;
            }

            Reflect v1 = Reflect.on(v0_1);
            Logger.d("Plugin", "from " + arg12);
            Logger.d("Plugin", "from " + arg12 + " activityThread = " + v0_1);
            v0_1 = v1.getFieldValue("mPackages", new Class[0]);
            if (!Logger.debug()) {
                return;
            }

            if (v0_1 == null) {
                return;
            }

            Iterator v4 = ((Map) v0_1).keySet().iterator();
            Object v2 = null;
            do {
                label_36:
                if (!v4.hasNext()) {
                    return;
                }

                v2 = v4.next();
                v1_1 = ((WeakReference) ((Map) v0_1).get(v2)).get();
                Logger.d("Plugin", "from " + arg12 + " key = " + v2);
                Logger.d("Plugin", "from " + arg12 + " value = " + v1_1);
                if (v2.equals(arg11.getPackageName())) {

                }
            } while (!v2.equals(arg11.getPackageName()));

            v1_1 = Reflect.on(v1_1).getFieldValue("mResources", new Class[0]);
            v5 = ((Resources) v1_1).getAssets();
            Logger.d("Plugin", "from " + arg12 + " Resources = " + String.valueOf(v1_1));
            Logger.d("Plugin", "from " + arg12 + " AssetManager isUpToDate = " + Reflect.on(v5).call("isUpToDate"));
            v2_1 = 1;
            while (true) {
                label_97:
                v1_1 = Reflect.on(v5).call("getCookieName", new Class[]{Integer.TYPE}, new Object[]{Integer.valueOf(v2_1)}).target;
                if (TextUtils.isEmpty(((CharSequence) v1_1))) {
                    break;
                }

                try {
                    File v6 = new File(((String) v1_1));
                    if (Logger.debug()) {
                        Logger.d("Plugin", "file = " + (((String) v1_1)) + " modifyTime " + v6.lastModified());
                    }
                    ++v2_1;
                    continue;
                } catch (Exception v1_2) {
                }
            }
        } catch (Exception v1_2) {
            v1_2.printStackTrace();
        }
    }

    public static Resources makeNewResource(Resources arg13, String[] arg14) {
        MyResources v1_2;
        MyResources v2_5;
        int v5;
        Object v1_1;
        int v4 = 1;
        Resources v3 = null;
        try {
            v1_1 = AssetManager.class.newInstance();
            Reflect v6 = Reflect.on(v1_1);
            Set v7 = PluginUtil.mergeRes(((AssetManager) v1_1), new LinkedHashSet());
            int v8 = arg14.length;
            v5 = 0;
            while (v5 < v8) {
                String v2 = arg14[v5];
                if (Logger.debug()) {
                    Logger.d("Plugin", "addAssetPath = " + v2);
                }

                if (!v7.contains(v2)) {
                    int v2_1 = ((Integer) v6.call("addAssetPath", new Class[]{String.class}, new Object[]{v2}).target).intValue();
                    if (Logger.debug()) {
                        Logger.d("Plugin", "cookieCount = " + v2_1);
                    }
                }
                ++v5;
                continue;
            }
        } catch (Exception v1) {
            return null;
        }
        try {
            while (true) {
                Object v2_3 = Reflect.on(v1_1).call("getCookieName", new Class[]{Integer.TYPE}, new Object[]{Integer.valueOf(v4)}).target;
                if (TextUtils.isEmpty(((CharSequence) v2_3))) {
                    break;
                }

                if (Logger.debug()) {
                    Logger.d("Plugin", "getPath = " + (((String) v2_3)) + " cookie = " + v4);
                }
                ++v4;
                continue;
            }
        } catch (Exception v2_2) {

        }
        if (arg13 != null) {
            try {
                if (arg13.getClass().getName().equals("android.content.res.MiuiResources")) {
                    Constructor v2_4 = Class.forName("android.content.res.MiuiResources").getDeclaredConstructor(AssetManager.class, DisplayMetrics.class, Configuration.class);
                    v2_4.setAccessible(true);
                    Resources resources = (Resources) v2_4.newInstance(v1_1, arg13.getDisplayMetrics(), arg13.getConfiguration());
                    return resources;
                }
            } catch (Exception v1) {
                return null;
            }
        }
        v2_5 = new MyResources(((AssetManager) v1_1), arg13.getDisplayMetrics(), arg13.getConfiguration());
        try {
            v2_5.setmBaseResources(arg13);
            v1_2 = v2_5;
        } catch (Exception v1) {
            v1_2 = v2_5;
        }
        return v1_2;
    }

    public static Set mergeRes(AssetManager arg7, Set arg8) {
        int v1 = 1;
        try {
            while (true) {
//                label_2:
                Object v0_1 = Reflect.on(arg7).call("getCookieName", new Class[]{Integer.TYPE}, new Object[]{Integer.valueOf(v1)}).target;
                if (TextUtils.isEmpty(((CharSequence) v0_1))) {
                    return arg8;
                }

                arg8.add(v0_1);
                if (Logger.debug()) {
                    Logger.d("Plugin", "getPath = " + (((String) v0_1)) + " cookie = " + v1);
                }

                ++v1;
                continue;
            }
        } catch (Exception v0) {
            return arg8;
        }
    }

    public static boolean signEquals(Context arg6, Signature[] arg7, Signature[] arg8) {
        boolean v0 = false;
        if (arg7 != null && arg8 != null && arg7.length == arg8.length) {
            if (Logger.debug()) {
                Logger.d("Plugin", "PluginManager signEquals start");
            }

            try {
                if (!Logger.debug()) {
                    PluginDepend v2 = com.bytedance.common.plugin.a.getPluginDepend();
                    arg6.getApplicationContext();
                    if (!"local_test".equals(v2.getChannel())) {
                        HashSet v2_1 = new HashSet();
                        int v3 = arg7.length;
                        int v1_1;
                        for (v1_1 = 0; v1_1 < v3; ++v1_1) {
                            v2_1.add(arg7[v1_1]);
                        }

                        HashSet v3_1 = new HashSet();
                        int v4 = arg8.length;
                        for (v1_1 = 0; v1_1 < v4; ++v1_1) {
                            v3_1.add(arg8[v1_1]);
                        }

                        return v2_1.equals(v3_1);
                    }
                }

                v0 = true;
            } catch (Exception v1) {
            }
        }

        return v0;
    }

    public static JSONArray toJsonArray(List arg3) {
        JSONArray v1 = new JSONArray();
        if (arg3 != null && !arg3.isEmpty()) {
            Iterator v2 = arg3.iterator();
            while (v2.hasNext()) {
                v1.put(v2.next());
            }
        }

        return v1;
    }

    public static List toList(JSONArray arg4) {
        ArrayList v1 = new ArrayList();
        if (arg4 != null && arg4.length() > 0) {
            int v2 = arg4.length();
            int v0;
            for (v0 = 0; v0 < v2; ++v0) {
                ((List) v1).add(arg4.optString(v0));
            }
        }

        return ((List) v1);
    }

    public static void writeToFile(InputStream arg6, File arg7) throws IOException {
        int v5 = 1024;
        BufferedOutputStream v0 = new BufferedOutputStream(new FileOutputStream(arg7));
        byte[] v1 = new byte[v5];
        while (true) {
            int v2 = arg6.read(v1, 0, v5);
            if (v2 == -1) {
                break;
            }

            v0.write(v1, 0, v2);
        }

        v0.close();
    }

    public static void writeToFile(byte[] arg8, File arg9) throws IOException {
        long v2_1;
        FileChannel v0_1 = null;
        FileOutputStream v6 = null;
        ReadableByteChannel v1 = null;
        try {
            v1 = Channels.newChannel(new ByteArrayInputStream(arg8));
            v6 = new FileOutputStream(arg9);
            v0_1 = v6.getChannel();
            v2_1 = 0;
            v0_1.transferFrom(v1, v2_1, ((long) arg8.length));
        } catch (Throwable v2_2) {

        } finally {
            try {
                v1.close();
            } catch (Exception e) {

            }
            try {
                v6.close();
            } catch (Exception e) {

            }

            try {
                v0_1.close();
            } catch (Exception e) {

            }
        }
    }
}

